'use strict';

import  React, {Component} from 'react';
import  {ListView, StyleSheet, Text, TouchableHighlight, View} from  'react-native';
import  style from  './styles';

const styles = StyleSheet.create(style);

class WatchFace extends Component {
    static propTypes = {
        sectionTime: React.PropTypes.string.isRequired,
        totalTime: React.PropTypes.string.isRequired
    }

    render() {
        return (
            <View style={style.watchFaceContainer}>
                <Text style={styles.sectionTime}>{this.props.sectionTime}</Text>
                <Text style={styles.totalTime}>{this.props.totalTime}</Text>
            </View>
        )
    }
}

class WatchControl extends Component {
    static propTypes = {
        stopWatch: React.PropTypes.func.isRequired,
        clearRecord: React.PropTypes.func.isRequired,
        startWatch: React.PropTypes.func.isRequired,
        addRecord: React.PropTypes.func.isRequired,
    }

    constructor(props) {
        super(props);

        this.state={
            watchOn:false,
            startBtnText:'启动',
            startBtnColor:'#60B644',
            stopBtnText:'计次',
            underlayColor:'#fff',
        };
    }

    _startWatch(){
        if(!this.state.watchOn){
            this.props.startWatch();
            this.setState({
                watchOn:true,
                startBtnText:'停止',
                startBtnColor:'#ff0044',
                stopBtnText:'计次',
                underlayColor:'#eee',
            });
        }else{
            this.props.stopWatch();
            this.setState({
                watchOn:false,
                startBtnText:'启动',
                startBtnColor:'#60B644',
                stopBtnText:'复位',
                underlayColor:'#eee',
            })
        }
    }

    _addRecord(){
        if(this.state.watchOn){
            this.props.addRecord();
        }else {
            this.props.clearRecord();
            this.setState({
                stopBtnText:'计次',
            });
        }
    }

    render() {
        return (<View  style={styles.watchControlContainer}>
            <View style={{flex:1,alignItems:'flex-start'}}>
                <TouchableHighlight style={styles.btnStop} underlayColor={this.state.underlayColor} onPress={()=>this._addRecord()}>
                    <Text style={styles.btnStopText}>{this.state.stopBtnText}</Text>
                </TouchableHighlight>
            </View>
            <View style={{flex:1,alignItems:'flex-end'}}>
                <TouchableHighlight style={styles.btnStart} underlayColor={this.state.underlayColor} onPress={()=>this._startWatch()}>
                    <Text style={[styles.btnStartText,{color:this.state.startBtnColor}]}>{this.state.startBtnText}</Text>
                </TouchableHighlight>
            </View>
        </View>);
    }


}
class  WatchRecord extends Component{
    static propRypes = {
        record:React.PropTypes.array.isRequired,
    }
    render(){
        let ds = new ListView.DataSource({rowHasChanged:(r1,r2)=>r1 !=r2});
        let theDataSource = ds.cloneWithRows(this.props.record);
        return (
            <ListView style={styles.recordList} dataSource={theDataSource}  enableEmptySections={true} renderRow = {(rawData)=>
               <View style={styles.recordItem}>
                   <Text style={styles.recordItemTitle}>{rawData.title}</Text>
                   <View style={{alignItems:'center'}}>
                        <Text style={styles.recordItemTime}>{rawData.time}</Text>
                   </View>
               </View>}/>
    );
    }
}

export  default  class   extends Component {
    constructor(){
        super();
        this.state = {
            stopWatch:false,
            resetWatch:true,
            initialTime:0,
            currentTime:0,
            recordTime:0,
            timeAccumulation:0,
            totalTime:'00:00.00',
            sectionTime:'00:00.00',
            recordCounter:0,
            record:[]
        }
    }
    componentWillUnmount() {
        this._stopWatch();
        this._clearRecord();
    }
    _startWatch(){
        if (this.state.resetWatch){
            this.setState({
                stopWatch:false,
                resetWatch:false,
                timeAccumulation:0,
                initialTime:(new Date()).getTime()
            });
        }else{
            this.setState({
                stopWatch:false,
                initialTime:(new Date()).getTime()
            });
        }

        let milSecond,second,minute,countingTime,secMilSecond,secSecond,secMinute,secCountingTime;
        let interval = setInterval(()=>{
            this.setState({
                currentTime:(new Date()).getTime()
            });

            countingTime = this.state.timeAccumulation + this.state.currentTime - this.state.initialTime;
            minute = Math.floor(countingTime/(60*1000));
            second = Math.floor((countingTime-60000*minute)/1000);
            milSecond = Math.floor((countingTime%1000)/10);
            secCountingTime = countingTime - this.state.recordTime;
            secMinute = Math.floor(secCountingTime/(60*1000));
            secSecond = Math.floor((secCountingTime - 60000 * secMinute)/1000);
            secMilSecond = Math.floor((secCountingTime%1000)/10);

            this.setState({
                totalTime:`${minute<10?'0'+minute:minute}:${second<10?'0'+second:second}.${milSecond<10? "0"+milSecond:milSecond}`,
                sectionTime:`${secMinute<10?'0'+secMinute:secMinute}:${secSecond<10?'0'+secSecond:secSecond}.${secMilSecond<10? "0"+secMilSecond:secMilSecond}`
            });

            if (this.state.stopWatch){
                this.setState({
                    timeAccumulation:countingTime
                })
                clearInterval(interval);
            }
    },10)


    }
    _stopWatch() {
        this.setState({
            stopWatch: true
        })
    }
    _addRecord(){
        let {recordCounter,record} = this.state;
        recordCounter ++ ;
        // if (recordCounter<8){
        //     record.pop();
        // }

        record.unshift({title:'计次'+recordCounter,time:this.state.sectionTime});
        this.setState({
            recordTime:this.state.timeAccumulation + this.state.currentTime - this.state.initialTime,
            recordCounter,
            record
        });
    }
    _clearRecord(){
        this.setState( {
            stopWatch:false,
            resetWatch:true,
            initialTime:0,
            currentTime:0,
            recordTime:0,
            timeAccumulation:0,
            totalTime:'00:00.00',
            sectionTime:'00:00.00',
            recordCounter:0,
            record:[]
        });
    }

    render(){
        return(
            <View style={styles.watchContainer}>
                <WatchFace totalTime = {this.state.totalTime} sectionTime = {this.state.sectionTime}></WatchFace>
                <WatchControl addRecord={()=>this._addRecord()}  clearRecord={()=>this._clearRecord()} startWatch={()=>this._startWatch()} stopWatch={()=>this._stopWatch()}></WatchControl>
                <WatchRecord record={this.state.record}></WatchRecord>
            </View>
    )
    }
}










